package com.hubei.control;

import com.hubei.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user_delete.action")
public class UserDeleteControl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取要删除的用户ID
        String idStr = request.getParameter("id");
        
        // 参数校验
        if (idStr == null || idStr.isEmpty()) {
            request.setAttribute("delErr", "删除失败：用户ID不能为空");
            request.getRequestDispatcher("./user_list.action").forward(request, response);
            return;
        }
        
        try {
            int id = Integer.parseInt(idStr);
            UserService service = UserService.getInstance();
            boolean success = service.deleteUser(id);
            
            if (success) {
                response.sendRedirect("./user_list.action");
            } else {
                request.setAttribute("delErr", "删除失败：用户不存在或数据库错误");
                request.getRequestDispatcher("./user_list.action").forward(request, response);
            }
        } catch (NumberFormatException | IOException e) {
            request.setAttribute("delErr", "删除失败：无效的用户ID格式");
            request.getRequestDispatcher("./user_list.action").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}